<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Repositories\URIAndUsersMenuRepository;
use App\Repositories\UsersRolesInMenuRepository;
use Log;
class CheckUsersPermissions
{
    public function __construct(URIAndUsersMenuRepository $URIAndUsersMenuRepository, UsersRolesInMenuRepository $UsersRolesInMenuRepository)
    {

        $this->URIAndUsersMenuRepository = $URIAndUsersMenuRepository;
        $this->UsersRolesInMenuRepository = $UsersRolesInMenuRepository;

    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
     
        if (!$this->inExceptArray($request)) {
            $uri = $request->route()->uri();

            $model = $this->URIAndUsersMenuRepository->findBy('URI', $uri, ['MenuID']);
            
            if ($model) {
                $user = auth('users')->user();
                if (!$this->UsersRolesInMenuRepository->HasPermissions($model->MenuID, $user->ID)) {
                    abort(403);
                }
            }
            else {
                Log::Info('漏网之鱼');
                Log::Info($uri);
            }
      
        }
        return $next($request);
    }
    protected $except = [
        'api/users/menu',
        'api/users/refresh',
    ];
    /**
     * Determine if the request has a URI that should pass through CSRF verification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function inExceptArray($request)
    {
        foreach ($this->except as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            if ($request->is($except)) {
                return true;
            }
        }

        return false;
    }
}
